<?php
!defined('IN_FRAME') && die('404 Page');
class m_cat extends Model {
    
    /* id,name,name_en,parent_id,seo_t,seo_k,seo_d,list_order,rec_status,created_at */
    
    public $objTreeList = null;
    
    public function __construct() {
        $this->table = 't_cat';
        parent::__construct();
        $this->objTreeList = $this->getTree();
    }
    
    private function setCacheStorage() {
        phpFastCache::$storage = 'files';
        phpFastCache::$securityKey = 'cat';
        phpFastCache::$path = CACHES_PATH;
    }
    
    private function refresh() {
        $this->objTreeList = $this->getTree(false);
    }
    
    public function insert($arrData) {
        $re = parent::insert($arrData);
        $re && $this->refresh();
        return $re;
    }
    
    public function update($arrSet, $arrWhere) {
        $re = parent::update($arrSet, $arrWhere);
        $re && $this->refresh();
        return $re;
    }
    
    public function delete($arrWhere) {
        $re = parent::delete($arrWhere);
        $re && $this->refresh();
        return $re;
    }
    
    public function getTree($blnFromCache = true) {
        $this->setCacheStorage();
        $objRe = null;
        if ($blnFromCache) {
            $objRe = phpFastCache::get('cat_cache');
            if (!$objRe) {
                $objRe = $this->getTree(false);
            }
        } else {
            $objRe = new TreeList($this->select(array(), '*', 'ORDER BY `list_order`, `id`'));
            phpFastCache::set('cat_cache', $objRe, 86400000); // 缓存一千天,Haha...
        }
        return $objRe;
    }
    
    public function getBackPathLinks($catid, $blnOnlySelf = false, $strItem = '/index.php?m=admin&c=content&cat_id=__CAT_ID__') {
        $strRe = '';
        if ($catid > 0) {
            $arrAll = $this->objTreeList->arrIdAll;
            $strItem = HTTP_URL . $strItem;
            $strRe = '<a href="' . str_replace('__CAT_ID__', $catid, $strItem) . '">' . $arrAll['_' . $catid]['name'] . '</a>';
            if (!$blnOnlySelf) {
                $arr = $this->objTreeList->arrIdBackPath['_' . $catid];
                foreach ($arr as $cid) {
                    $strRe = '<a href="' . str_replace('__CAT_ID__', $arrAll[$cid]['id'], $strItem) . '">' . $arrAll[$cid]['name'] . '</a><i class="icon-chevron-right"></i> ' . $strRe;
                }
            }
        } else {
            $strRe = '<a href="' . str_replace('__CAT_ID__', $catid, $strItem) . '">未指定栏目</a>';
        }
        return $strRe;
    }
    
    public function isName($str) {
        $int = mb_strlen($str, 'utf8');
        return (!Helper::hasBadword($str) && $int > 0 && $int <= 20);
    }
    
    public function isNameEn($str) {
        $arrTemp = array();
        preg_match('/^[0-9a-z]{1,20}$/', $str, $arrTemp);
        return count($arrTemp) > 0;
    }
    
}